//
//  UIViewController+HDAddNewCommunityController.m
//  app
//
//  Created by D on 15/8/21.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDAddNewCommunityController.h"
#import "HDAddNewComManager.h"
#import "HDAddNewComResult.h"
#import "HDNewComCell.h"
#import "HDAddMyCommunity.h"
#import "HDSelectContentController.h"
#import "HDSubmitComController.h"

static const CGFloat kCartTotalPanelHeight = 120;

@interface HDAddNewCommunityController ()<UITableViewDataSource,UITableViewDelegate,HDAddMyCommunityDelegate,MBProgressHUDDelegate,HDNewComCellDelegate>

@property (nonatomic,strong) HDAddNewComManager * addNewComManger;
@property (nonatomic,strong) HDAddNewComResult * addNewComResult;
@property (nonatomic,strong) HDAddNewComResult * addNew_submit;
@property (nonatomic,strong) UITableView * addTableView;
@property (nonatomic,strong) UIButton * backBtn;
@property (strong,nonatomic) MBProgressHUD* progress_;
@property (strong,nonatomic) UITextField * phoneTextField;

@end


@implementation HDAddNewCommunityController

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"添加我的小区";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.addTableView = [[UITableView alloc]initWithFrame:CGRectOf(CGPointMake(0, 64),
                                                                         [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kCartTotalPanelHeight oh:+56]) style:UITableViewStyleGrouped];
    self.addTableView.dataSource = self;
    self.addTableView.delegate = self;
    self.addTableView.scrollEnabled = NO;
    [self.view addSubview:self.addTableView];
    
    
    if (self.isAddNew == NO ) {
        //重写返回按钮
        self.backBtn = [[UIButton alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP],
                                                                [self.ubo ow:40 oh:40])];
        [self.backBtn setImage:[UIImage imageNamed:kImageMallSearchGrayArrowBackReturn] forState:UIControlStateNormal];
        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.backBtn addTarget:self action:@selector(leftBarBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.backBtn];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideCom:) name:UIKeyboardWillHideNotification object:nil];
    
#ifdef __IPHONE_5_0
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 5.0) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowCom:)name:UIKeyboardWillChangeFrameNotification object:nil];
    }
#endif

    
    
    
    self.addNewComManger = [HDAddNewComManager shareManager];
    self.addNew_submit = [[HDAddNewComResult alloc]initWithTarget:self action:@selector(submit_first:)];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
//    if ([[NSUserDefaults standardUserDefaults]boolForKey:@"savacom"])
//    {
//        [self.addTableView reloadData];
//    }

    
    if ([[[[NSUserDefaults standardUserDefaults] objectForKey:kReSelectDic] objectForKey:kReSelect] integerValue]) {
        
        NSDictionary * dict;
        
        switch ([[[[NSUserDefaults standardUserDefaults] objectForKey:kReSelectDic] objectForKey:kReSelectNo] integerValue]) {
            case 0:         //修改了小区
                //将组团,楼牌号,房间号置为空
                dict = @{@"group_name":@"",@"group_id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"community_zu"];          //组团
                dict = @{@"building_name":@"",@"id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"building"];         //楼牌号
                dict = @{@"house_name":@"",@"community_id":@"",@"id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"house"];            //房间号
                break;
            
            case 1:         //修改了组团
                //楼牌号,房间号置为空
                dict = @{@"building_name":@"",@"id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"building"];         //楼牌号
                dict = @{@"house_name":@"",@"community_id":@"",@"id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"house"];            //房间号

                break;
                
            case 2:         //修改了楼牌号
                //房间号置为空
                dict = @{@"house_name":@"",@"community_id":@"",@"id":@""};
                [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"house"];            //房间号
                break;
                
            default:
                break;
        }
    }
    
    [self.addTableView reloadData];
    
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self.phoneTextField resignFirstResponder];
}

-(void)leftBarBtnClicked:(UIButton*)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 键盘弹出时调用的方法
#pragma mark Responding to keyboard events
- (void)keyboardWillShowCom:(NSNotification*)notification {
    if (nil == self.phoneTextField) {
        return;
    }
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
    
    CGRect textFrame = self.phoneTextField.frame;//当前UITextView的位置
    float textY = textFrame.origin.y + textFrame.size.height;//得到UITextView下边框距离顶部的高度
    float bottomY = self.view.frame.size.height - textY;//得到下边框到底部的距离
//        if(bottomY >= keyboardRect.size.height ){//键盘默认高度,如果大于此高度，则直接返回
//    
//            return;
//        }
    float moveY = keyboardRect.size.height - bottomY;
    
//    [self moveInputBarWithKeyboardHeight:moveY withDuration:animationDuration];
    self.addTableView.frame = CGRectOf(CGPointMake(0, 64-keyboardRect.size.height/3*2),
                                       [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kCartTotalPanelHeight oh:+56]);
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboardNewCom:)];
//    [self.addTableView addGestureRecognizer:tap];
    
}

//键盘被隐藏的时候调用的方法
-(void)keyboardWillHideCom:(NSNotification*)notification {
    
    NSDictionary* userInfo = [notification userInfo];
    
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    
//    [self moveInputBarWithKeyboardHeight:0.0 withDuration:animationDuration];
    self.addTableView.frame = CGRectOf(CGPointMake(0, 64),
                                       [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kCartTotalPanelHeight oh:+56]);
  
}
#pragma mark 移动view
-(void)moveInputBarWithKeyboardHeight:(float)_CGRectHeight withDuration:(NSTimeInterval)_NSTimeInterval{
    
    CGRect rect = self.view.frame;
    
    rect.origin.y = -_CGRectHeight;//view往上移动
    
    self.view.frame = rect;
    
    
}




#pragma mark - tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString * cellIdentifier = @"cellIdentifier";
    HDNewComCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];

        cell = [[HDNewComCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier row:indexPath.row];
    if (indexPath.row == 0 || indexPath.row == 1 || indexPath.row == 2 || indexPath.row == 3) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }else if (indexPath.row == 7){
        self.phoneTextField = cell.namefld;
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    else
    {
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
        [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
       
    }
    
    [cell valueForCellWithRow:indexPath.row];
    
    return cell;

    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.row) {
        case 4:
        {
            //选择小区
            HDSelectContentController * selectView = [[HDSelectContentController alloc]init];
            selectView.sign = @"0";
            selectView.cmid = @"cmid";
            [self.navigationController pushViewController:selectView animated:YES];
            
        }
            break;
            
       
            
        case 5:
        {
            //楼牌号
            
            if ([[[[NSUserDefaults standardUserDefaults]objectForKey:@"community"] objectForKey:@"community_name"]length] > 0){
            
                HDSelectContentController * selectView = [[HDSelectContentController alloc]init];
                selectView.sign = @"2";
                selectView.cmid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"community"] objectForKey:@"community_id"];
                [self.navigationController pushViewController:selectView animated:YES];
                
            }else
            {
                UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"请选择小区" message:nil delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                [av show];
            }
            
            
        }
            break;
            
        case 6:
        {
            //房间号
            
            if ([[[[NSUserDefaults standardUserDefaults]objectForKey:@"building"] objectForKey:@"building_name"]length] > 0){
                HDSelectContentController * selectView = [[HDSelectContentController alloc]init];
                selectView.sign = @"3";
                selectView.cmid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"building"] objectForKey:@"id"];
                [self.navigationController pushViewController:selectView animated:YES];

                
            }else
            {
                UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"请选择小区" message:nil delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                [av show];
            }
            
        }
            break;
            
       
            
        default:
            break;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
        HDAddMyCommunity * addComView = [[HDAddMyCommunity alloc]initWithAdd:@"1"];
        addComView.delegate = self;
        return addComView;
}

-(void)next
{
    [self sendRequest];
}

-(void)addMyCommunityOrNext:(UIButton *)btn
{
    if (btn.tag == 2) {
        //下一步
        [self sendRequest];
        
        
    }
}
-(void)sendRequest
{
    [self.phoneTextField resignFirstResponder];
    
    if ([[[[NSUserDefaults standardUserDefaults]objectForKey:@"community"] objectForKey:@"community_name"]length] > 0  && [[[[NSUserDefaults standardUserDefaults]objectForKey:@"building"] objectForKey:@"building_name"]length] > 0 && [[[[NSUserDefaults standardUserDefaults]objectForKey:@"house"] objectForKey:@"house_name"]length] > 0 && [[[NSUserDefaults standardUserDefaults]objectForKey:@"comPhone"]integerValue] > 0) {
        self.progress_ = [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:self.progress_];
        [self.view bringSubviewToFront:self.progress_];
        self.progress_.delegate = self;
        [self.progress_ show:YES];
        
        NSDictionary * params = @{@"phone":[[NSUserDefaults standardUserDefaults]objectForKey:@"comPhone"],
                                  @"cmid":[[[NSUserDefaults standardUserDefaults]objectForKey:@"house"]objectForKey:@"community_id"],
                                  @"id":[[[NSUserDefaults standardUserDefaults]objectForKey:@"house"]objectForKey:@"id"]};
        
        [self.addNewComManger submitFirst:self.addNew_submit Params:params];
        
    }else
    {
        UIAlertView * av = [[UIAlertView alloc]initWithTitle:@"请填写地址" message:nil delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [av show];
    }
    
}
-(void)submit_first:(HDAddNewComResult*)rt
{
    if (self.progress_) {
        [self.progress_ removeFromSuperview];
        self.progress_ = nil;
    }
    
    if (rt.success) {
        
        HDSubmitComController * submitView = [[HDSubmitComController alloc]init];
        [self.navigationController pushViewController:submitView animated:YES];
        
    }
}
#pragma mark - 点击隐藏键盘
-(void)hideKeyboardNewCom:(UITapGestureRecognizer*)tap
{
    [tap removeTarget:self action:@selector(hideKeyboardNewCom:)];
    [self.phoneTextField resignFirstResponder];
}

@end








